import axios from 'axios';

// 创建axios实例
const authApi = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 获取存储的token
export const getToken = () => {
  return localStorage.getItem('token');
};

// 设置token
export const setToken = (token) => {
  localStorage.setItem('token', token);
};

// 移除token
export const removeToken = () => {
  localStorage.removeItem('token');
};

// 获取用户信息
export const getUserInfo = () => {
  const userInfo = localStorage.getItem('userInfo');
  return userInfo ? JSON.parse(userInfo) : null;
};

// 设置用户信息
export const setUserInfo = (userInfo) => {
  localStorage.setItem('userInfo', JSON.stringify(userInfo));
};

// 移除用户信息
export const removeUserInfo = () => {
  localStorage.removeItem('userInfo');
};

// JWT解析函数
const parseJwt = (token) => {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error('JWT解析错误:', error);
    return null;
  }
};

// 登录
export const login = async (mobile, password) => {
  try {
    // 调用后端登录接口
    const response = await authApi.post('/users/login', { 
      mobile, 
      password 
    });
    
    // 后端返回格式为 { code: 200, data: "JWT令牌", message: "请求成功" }
    if (response.data && response.data.code === 200) {
      const token = response.data.data;
      
      // 从JWT令牌中解析用户信息
      const decodedToken = parseJwt(token);

      // 构建用户信息对象
      const userInfo = {
        userId: decodedToken?.userId,
        userName: decodedToken?.sub,
        role: decodedToken?.role || 0,
        avatarUrl: decodedToken?.avatarUrl,
        mobile: mobile
      };
      
      // 存储token和用户信息
      setToken(token);
      setUserInfo(userInfo);
      
      return {
        success: true,
        token,
        userInfo
      };
    }
    
    return {
      success: false,
      message: response.data?.message || '登录失败，请检查账号和密码'
    };
  } catch (error) {
    console.error('登录失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '登录失败，请稍后再试'
    };
  }
};

// 注册
export const register = async (mobile, password, nickname, avatarBase64) => {
  try {
    // 实际项目中应该调用真实API
    // const formData = new FormData();
    // formData.append('mobile', mobile);
    // formData.append('password', password);
    // formData.append('nickname', nickname);
    // if (avatarBase64) {
    //   formData.append('avatar', avatarBase64);
    // }
    // const response = await authApi.post('/auth/register', formData, {
    //   headers: {
    //     'Content-Type': 'multipart/form-data'
    //   }
    // });
    // const { token, userInfo } = response.data;
    
    // 模拟API响应
    // 这里仅作为演示，实际项目中应该使用真实的后端API
    
    // 模拟手机号已存在的情况
    if (mobile === '13800138000') {
      return {
        success: false,
        message: '该手机号已被注册'
      };
    }
    
    // 模拟注册成功
    const token = 'mock_token_' + Date.now();
    const userInfo = {
      id: 'user_' + Date.now(),
      mobile: mobile,
      nickname: nickname,
      role: 1, // 普通用户角色
      avatarUrl: avatarBase64 || 'https://picsum.photos/id/1005/200/200'
    };
    
    // 存储token和用户信息
    setToken(token);
    setUserInfo(userInfo);
    
    return {
      success: true,
      token,
      userInfo
    };
  } catch (error) {
    console.error('注册失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '注册失败，请稍后再试'
    };
  }
};

// 退出登录
export const logout = () => {
  removeToken();
  removeUserInfo();
};

// 检查是否已登录
export const isLoggedIn = () => {
  return !!getToken();
};

// 检查是否是管理员
export const isAdmin = () => {
  const userInfo = getUserInfo();
  return userInfo && (userInfo.role === 2 || userInfo.role === 3);
};

// 请求拦截器，添加token
authApi.interceptors.request.use(
  config => {
    const token = getToken();
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default authApi;